package com.jiexinyun.dto.page;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiexinyun.dsl.SafeQueryDSL;
import com.jiexinyun.dto.request.common.BasePageReq;
import com.jiexinyun.utils.CommonUtils;
import com.jiexinyun.utils.simple.SimpleUtils;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * 为了不使用反射机制，每一个都重新写
 * 因为使用反射机制一个是写起来麻烦，第二个就是可能造成安全问题或者性能问题
 * @param <T>
 */
public class PageUtilsDto<T> {

    public SafeQueryDSL<T> queryDSL;

    public PageUtilsDto() {
        queryDSL = new SafeQueryDSL<>();
    }

    public final Page<T> getPageParam(BasePageReq req) {
        Page<T> pageParam = new Page<>();
        pageParam.setCurrent(req.getCurrent().longValue());
        pageParam.setSize(req.getSize().longValue());
        List<Map<String,String>> orders = req.getOrders();
        if(CommonUtils.isNotNull(orders)) {
            orders.forEach(order -> {
                String rawcolumn = order.get("column");
                //驼峰变下划线
                String column = SimpleUtils.camelToUnderline(rawcolumn);
                String orderType = order.get("sort");
                if(CommonUtils.isEmpty(column) || CommonUtils.isEmpty(orderType)){
                    //传参不合理，走下一轮
                    return;
                }
                if(orderType.equals("asc")) {
                    pageParam.addOrder(OrderItem.asc(column));
                }else{
                    pageParam.addOrder(OrderItem.desc(column));
                }
            });
        } else {
            pageParam.addOrder(OrderItem.desc("sort"));
        }
        return pageParam;
    }

    /**
     * 直接传递到mybatis中使用
     * @return
     */
    public static String getOrderStr() {
        return "order by code_table_id asc,sort asc";
    }

    public final LambdaQueryWrapper<T> getWrapper(T entity) {
        return queryDSL.getWrapper();
    }

    public <T> T createInstance(Supplier<T> supplier) {
        return supplier.get();
    }
}
